/*
 * Filename: e:\OwnProject\FlutterPro\flutter_app_01\lib\views\form\model.dart
 * Path: e:\OwnProject\FlutterPro\flutter_app_01\lib\views\form
 * Created Date: Friday, April 2nd 2021, 2:45:01 pm
 * Author: chenfayun
 * 
 * Copyright (c) 2021 Your Company
 */

import '../../public.dart';

class FormViewModal extends ViewStateModel {
  TextEditingController nameTextEditingController = TextEditingController();
  TextEditingController idTextEditingController = TextEditingController();
  TextEditingController pwdTextEditingController = TextEditingController();
  TextEditingController remarkTextEditingController = TextEditingController();
  late AccountItem account;
  bool isEdit = false;

  FormViewModal(AccountItem orgin) {
    if (orgin.id != null) {
      isEdit = true;
      nameTextEditingController.text = orgin.name ?? '';
      idTextEditingController.text = orgin.id ?? '';
      pwdTextEditingController.text = orgin.pwd ?? '';
      remarkTextEditingController.text = orgin.remark ?? '';
    }
    account = orgin;
  }

  Future<AccountItem> save() async {
    String name = nameTextEditingController.text;
    String id = idTextEditingController.text;
    String pwd = pwdTextEditingController.text;
    String remark = remarkTextEditingController.text;
    AccountItem form = AccountItem(
      id: id,
      name: name,
      pwd: pwd,
      remark: remark,
      type: account.type,
    );
    try {
      await Validate.validator(form.toJSONEncodable(), {
        'name': [
          {'required': true, 'msg': 'Please input name'},
        ],
        'id': [
          {'required': true, 'msg': 'Please input ID'},
        ],
        'pwd': [
          {'required': true, 'msg': 'Please input account password'},
        ],
      });
      return Future.value(form);
    } on String catch (msg) {
      Toast.show(msg);
      return Future.error(msg);
    }
  }

  @override
  void dispose() {
    super.dispose();
    nameTextEditingController.dispose();
    idTextEditingController.dispose();
    pwdTextEditingController.dispose();
    remarkTextEditingController.dispose();
  }
}
